<?php

/**
 *liumen&Jackie Yang
 */
class ctrl_admin extends ctrl_base {


    private static $dirName = 'admin';
    private static $adminTypes = array('1'	=> '超级管理员','2'	=> '普通管理员');

    /**
     * 后台用户列表页面
     */    
    public static function main() {
    	if(!model_admin::islogin()){
           header("location:/index.php?act=admin&st=adminLogin");die();
    	}else{
			self::sys_func();
			$userinfo = model_user::get_userinfo_byId($_SESSION['admin']['userid']);
			$userinfo['admin_type'] = self::$adminTypes[$userinfo['admin_type']];
			self::smarty()->assign('userinfo', $userinfo);
			self::smarty()->assign('year', date("Y"));
    		self::smarty()->display(self::$dirName . '/admin_index.html');
    		exit;
    	}
    }

    /**
     * 添加用户页面
     */
    public static function adminAdd() {
    	//$ret = base64_encode('/?act=admin&st=adminAdd');
    	if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		self::smarty() -> assign('min_password', MIN_PASSWORD);
        self::smarty() -> display(self::$dirName . '/admin_add.html');
    }

    /**
     * 编辑
     */
    public static function adminEdit() {
    	if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		self::operation(array('admin_user_edit'));
    	$userid = isset($_GET['userid'])? intval($_GET['userid']):$_SESSION['admin']['userid'];
    	$userInfo = model_user::get_userinfo_byId($userid);
    	$show_operator = $_SESSION['admin']['admin_type'] == 1? true:false;//是否具有超级管理员权限
		$supper_auth = self::supper_auth($_SESSION['admin']['username']);
		self::smarty()->assign('supper_auth', $supper_auth);
		self::smarty()->assign('userid', $userid);
		self::smarty()->assign('show_operator', $show_operator);
		self::smarty()->assign('adminType', self::$adminTypes);
		self::smarty()->assign('current_user_id', $_SESSION['admin']['userid']);
        self::smarty()->assign('userInfo', $userInfo);
		self::smarty() -> assign('min_password', MIN_PASSWORD);
        self::smarty()->display(self::$dirName . '/admin_edit.html');
    }
    /*
     * 保存编辑内容
     */
    public static function adminModify() {
    	//$ret = base64_encode('/?act=admin&st=adminModify');
    	if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		self::operation(array('admin_user_edit'));
    	$userid = isset($_POST['admin_user_id'])? intval($_POST['admin_user_id']):$_SESSION['admin']['userid'];
    	$data = array(
    			'user_name' => isset($_POST['user_name'])? trim($_POST['user_name']):'',
    			'real_name' => isset($_POST['real_name'])? trim($_POST['real_name']):'',
				'phone' => isset($_POST['phone'])? trim($_POST['phone']):'',
				'email' => isset($_POST['email'])? trim($_POST['email']):'',
				'part' => isset($_POST['part'])? trim($_POST['part']):'',
    	);
    	if(empty($data['user_name'])) {
			self::ajax_ouput(300, '用户名不能为空');
    	}
    	$user_pwd = trim($_POST['user_pwd']);
    	if(!empty($user_pwd)) {
    		if($user_pwd == trim($_POST['user_comfirm_pwd'])) {
    			$data['user_pwd'] = sha1($user_pwd);
    		} else {
				self::ajax_ouput(300, '两次输入的密码不一致');
    		}
    	}
    	$userInfo = model_user::get_userinfo_byId($userid);
    	if($data['user_name'] != $userInfo['user_name']) {  //新老用户名不一致，即修改用户名
    		$num = model_user::exists_username($data['user_name']);
    		if($num > 0) {
				self::ajax_ouput(300, '该用户名已存在，请用其他用户名！');
    		}
    	}
    	//修改用户分组
    	if($_SESSION['admin']['admin_type'] == '1' && $_SESSION['admin']['userid'] != $userid) {//有修改权限，同时不是修改自己的
    		$data['admin_type'] = isset($_POST['admin_type'])? intval($_POST['admin_type']):2;
    	}
    	$result = model_user::update_user_info(explode(',',$userid), $data);
    	self::ajax_ouput(200, '操作成功', 'manger_admin', 'closeCurrent');
    }

    public static function adminDelete() {
    	if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		self::operation(array('admin_user_delete'));
        $user_id = isset($_POST['ids'])? $_POST['ids']:0;
		$user_id = explode(',', $user_id);
		foreach($user_id as $v){
			$users[] = intval($v);
		}
      	$data = array('delete_flag' => 1);
        $st = model_user::update_user_info($users, $data);
        if($st > 0) {
        	self::ajax_ouput(200, '操作成功','manger_admin');
        } else {
        	self::ajax_ouput(300, '操作失败');
        }
    }

    public static function adminIndex() {
    	self::main();
    }
   
    /*
     * 管理员登录控制器
     * Jackie Yang修改
     * */
    public static function adminLogin() {
		if(model_admin::islogin()){
           header("location:/");die();
    	}
    	$ret = isset($_GET['ret'])? trim($_GET['ret']):'';
    	self::smarty()->assign('ret',$ret);//登录成功后，跳转目标
        self::smarty()->display(self::$dirName . '/admin_login.html');
    }
    /*
     * 登录操作
     */
    public static function do_login() {
    	$userInfo = array();
    	$userInfo['username'] = trim($_POST['username']);
    	if(empty($userInfo['username'])) {
			self::ajax_ouput(300, '请输入用户名！');
    	}
    	$userInfo['password'] = sha1(trim($_POST['password']));
    	if(empty($userInfo['password'])) {
    		self::ajax_ouput(300, '请输入密码！');
    	}
    	$ret = isset($_POST['ret'])? trim($_POST['ret']):'';
    	$check_code = trim($_POST['chkcode']);
    	if(strtolower($check_code) != strtolower($_SESSION['code_adminLogin'])){
			self::ajax_ouput(300, '验证码不正确');
   		}
    	
    		$data= model_user::get_userinfo_by_username($userInfo['username']);
    		if(is_array($data) && count($data)>0) {
    			if($userInfo['password'] == $data['user_pwd']) {   //密码匹配
    				if($data['status'] == '0') { //账户被禁用 
						self::ajax_ouput(300, '该账户已被禁用，请联系系统管理员！');
    				}
    				$update_data['last_login_ip'] = framework_static_base::real_ip();
    				$update_data['last_login_time'] = date('Y-m-d H:i:s');
    				$update_data['login_count'] = $data['login_count'] + 1;
    				$rs = model_user::update_user_info(explode(',',$data['admin_user_id']), $update_data);
    				if($rs>0) {
    					$_SESSION['admin'] = array(
    							'userid' => $data['admin_user_id'],
    							'username' => $data['user_name'],
    							'admin_type' => $data['admin_type'],
    					);
						$refushTarget = empty($_POST['refushTarget'])?'':$_POST['refushTarget'];
						$host_url = empty($_POST['refushTarget'])?HOST_URL:'';
						self::ajax_ouput(200, '登录成功！',$refushTarget, 'closeCurrent', $host_url);
    				} else {
						self::ajax_ouput(300, '系统繁忙，稍后重试！');
    				}
    			} else {
					self::ajax_ouput(300, '用户名或密码不正确');
    			}
    		} else {
				self::ajax_ouput(300, '用户名或密码不正确');
    		}
    }
    /*
     * 新增管理员
     */
    public static function insert_admin_user() {
        if(!model_admin::islogin()) {
    		self::goto_login();
    	} 
    	$data = array(
    		'user_name' => isset($_POST['user_name'])? trim($_POST['user_name']):'',
    		'user_pwd' => isset($_POST['user_pwd'])? trim($_POST['user_pwd']):INIT_PASSWORD,
    		'real_name' => isset($_POST['real_name'])? trim($_POST['real_name']):'',
    		'admin_type' => isset($_POST['admin_type'])? intval($_POST['admin_type']):2,
			'phone' => isset($_POST['phone'])? trim($_POST['phone']):'',
			'email' => isset($_POST['email'])? trim($_POST['email']):'',
			'part' => isset($_POST['part'])? trim($_POST['part']):'',
    	);
    	if(empty($data['user_name'])) {
			self::ajax_ouput(300, '用户名不能为空');
    	}   	
    	if(empty($data['user_pwd'])) {
			self::ajax_ouput(300, '密码不能为空');
    	}
		if(strlen($data['user_pwd']) < MIN_PASSWORD){
			self::ajax_ouput(300, '密码不能小于'.MIN_PASSWORD.'位');
		}
    	if($data['user_pwd'] != trim($_POST['user_comfirm_pwd'])) {
			self::ajax_ouput(300, '两次输入的密码不一致');
    	}
		if(empty($data['phone'])) {
			self::ajax_ouput(300, '手机号不能为空');
    	}  
		if(empty($data['email'])) {
			self::ajax_ouput(300, '邮箱不能为空');
    	}  
		if(empty($data['part'])) {
			self::ajax_ouput(300, '公司部门及职位不能为空');
    	} 
    	$num = model_user::exists_username($data['user_name']);
    	if($num > 0) {
			self::ajax_ouput(300, '该用户名已存在，请用其他用户名！');
    	}
		$exists = model_user::exists_value_key('phone', $data['phone']);
		if($exists > 0){
			self::ajax_ouput(300, '该手机号已存在，请用其他手机号！');
		}
		$exists = model_user::exists_value_key('email', $data['email']);
		if($exists > 0){
			self::ajax_ouput(300, '该邮箱已存在，请用其他邮箱！');
		}
    	$data['user_pwd'] = sha1($data['user_pwd']);//密码以sha1加密
    	$result = model_user::add_user($data);
    	if($result == 0) {
			self::ajax_ouput(300, '操作失败');
    	} else {
			self::ajax_ouput(200, '操作成功','manger_admin', 'closeCurrent');
    	}
    }
    
    public static function admin_user_list() {
   		if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		self::operation(array('admin_user_list'));
    	$currentPage = isset($_POST['pageNum']) ? trim($_POST['pageNum']) : 1;
		$pagesize = isset($_POST['numPerPage']) ? $_POST['numPerPage'] : self::$_pagesize;
		$nextpage = ($currentPage - 1) * $pagesize;
		$user_name = isset($_POST['user_name']) ? trim($_POST['user_name']) : '';
		$real_name = isset($_POST['real_name']) ? trim($_POST['real_name']) : '';

		$condition = array();
		if(!empty($user_name)){
			$condition['user_name'] = $user_name;
		}
		if(!empty($real_name)){
			$condition['real_name'] = $real_name;
		}
      	$allUsers = model_user::user_list(array('page'=>$currentPage,'rows'=>$pagesize), $condition);
        $total = model_user::get_user_count();
        self::smarty()->assign('allUsers', $allUsers);
        $pageShow = framework_static_common::page($pagesize, $total, $currentPage);
        $show_operator = $_SESSION['admin']['admin_type'] == 1? true:false;//是否具有超级管理员权限
		$supper_auth = self::supper_auth($_SESSION['admin']['username']);
		self::smarty()->assign('supper_auth', $supper_auth);
        self::smarty()->assign('adminType', self::$adminTypes);
        self::smarty()->assign('show_operator', $show_operator);
        self::smarty()->assign('pageShow', $pageShow);

		//新添加
		self::smarty() -> assign('total', $total);
		self::smarty() -> assign('pageNum', $currentPage);
		self::smarty() -> assign('numPerPage', $pagesize);
		self::smarty() -> assign('pageNumShown', ceil($total/$pagesize));
		self::smarty() -> assign('shoNum', self::$_shoNum);
		self::smarty() -> assign('user_name', $user_name);
		self::smarty() -> assign('real_name', $real_name);

        self::smarty()->display(self::$dirName . '/admin_list.html');
    }

    public static function check_code(){
    	ob_clean();
        header("Content-type: image/png");
         //创建真彩色白纸
         $im = @imagecreatetruecolor(50, 20) or die("建立图像失败");
         //获取背景颜色
         $background_color = imagecolorallocate($im, 255, 255, 255);
         //填充背景颜色(这个东西类似油桶)
         imagefill($im,0,0,$background_color);
        //获取边框颜色
         $border_color = imagecolorallocate($im,200,200,200);
         //画矩形，边框颜色200,200,200
         imagerectangle($im,0,0,49,19,$border_color);
         //逐行炫耀背景，全屏用1或0
         for($i=2;$i<18;$i++){
                   //获取随机淡色
                   $line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255));
                   //画线
                   imageline($im,2,$i,47,$i,$line_color);
         }
         //设置字体大小
         $font_size=11;
         //设置印上去的文字
         $Str[0] = "ABCDEFGHIJKMNPRSTUVWX";
         $Str[1] = "abcdefghijkmnpqrstuvw";
         $Str[2] = "234567892345678923456";
         //获取第1个随机文字
         $imstr[0]["s"] = $Str[rand(0,2)][rand(0,20)];
         $imstr[0]["x"] = rand(2,5);
         $imstr[0]["y"] = rand(1,4);
         //获取第2个随机文字
         $imstr[1]["s"] = $Str[rand(0,2)][rand(0,20)];
         $imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1);
         $imstr[1]["y"] = rand(1,3);
         //获取第3个随机文字
         $imstr[2]["s"] = $Str[rand(0,2)][rand(0,20)];
         $imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1);
         $imstr[2]["y"] = rand(1,4);
         //获取第4个随机文字
         $imstr[3]["s"] = $Str[rand(0,2)][rand(0,20)];
         $imstr[3]["x"] = $imstr[2]["x"]+$font_size-1+rand(0,1);
         $imstr[3]["y"] = rand(1,3);
         $imgcode = '';
         //写入随机字串
         for($i=0;$i<4;$i++){
                   //获取随机较深颜色
                   $text_color = imagecolorallocate($im,rand(50,180),rand(50,180),rand(50,180));
                   //画文字
                   imagechar($im,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imstr[$i]["s"],$text_color);
         }
         //显示图片
         imagepng($im);
          //销毁图片
         imagedestroy($im);
         //定义session
         $_SESSION['code_adminLogin'] = $imstr[0]["s"].$imstr[1]["s"].$imstr[2]["s"].$imstr[3]["s"];
         framework_static_function::write_log($_SESSION['code_adminLogin'],"vcode");
    }
    /*
     * 退出
     * Jackie Yang修改
     * */
    public static function adminLogoutAction() {
		session_destroy();
    	unset($_SESSION);
		framework_static_function::refreshframe();
    }


    /*
     * 用户基本信息
     * Jackie Yang
     * */
    public function userinfo(){
    $ret = base64_encode('/?act=admin&st=userinfo');
    	if(!model_admin::islogin()) {
    		self::goto_login($ret);
    	}
        $userinfo = model_user::get_userinfo_byId($_SESSION['admin']['userid']);
        
        $userinfo['admin_type'] = self::$adminTypes[$userinfo['admin_type']];
        self::smarty()->assign('userinfo', $userinfo);
        self::smarty()->display(self::$dirName . '/admin_info.html');
    }
	//服务器信息
	private static function sys_func(){
		$sys_info['os']            = PHP_OS;
		$sys_info['ip']            = $_SERVER['SERVER_ADDR'];
		$sys_info['web_server']    = $_SERVER['SERVER_SOFTWARE'];
		$sys_info['php_ver']       = PHP_VERSION;
		//$sys_info['mysql_ver']     = $mysql_ver;
		$sys_info['timezone']      = date_default_timezone_get();
		$sys_info['max_filesize'] = ini_get('upload_max_filesize');
		$sys_info['mysql_verion'] = model_admin::get_mysql_version();
		self::smarty()->assign('sys_info', $sys_info);
	}

	//登录对话框
	public static function login_dialog(){
		self::smarty()->display(self::$dirName . '/admin_login_dialog.html');
	}
	//修改自己的密码
	public static function modify_pwd(){
		if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		self::operation(array('modify_pwd'));
		if($_POST){
			$old_pwd = trim($_POST['user_old_pwd']);
			if(empty($old_pwd)){
				self::ajax_ouput(300, '请输入原密码');
			}
			$old_pwd = sha1($old_pwd);
			$new_pwd = trim($_POST['user_new_pwd']);
			if(empty($new_pwd)){
				self::ajax_ouput(300, '请输入新密码');
			}
			$new_pwd = sha1($new_pwd);
			$confirm_pwd = trim($_POST['user_confirm_pwd']);
			if(empty($confirm_pwd)){
				self::ajax_ouput(300, '请输入确认密码');
			}
			$confirm_pwd = sha1($confirm_pwd);
			if($new_pwd != $confirm_pwd){
				self::ajax_ouput(300, '新密码和确认密码不一致');
			}
			if($new_pwd == $old_pwd){
				self::ajax_ouput(300, '修改密码和原密码不能一致');
			}
			$user_id = $_SESSION['admin']['userid'];
			$user_info = model_user::get_userinfo_byId($user_id);
			if($old_pwd != $user_info['user_pwd']){
				self::ajax_ouput(300, '原密码输入有误');
			}
			$update_data['user_pwd'] = $new_pwd;
			$result = model_user::update_user_info(explode(',',$user_id), $update_data);
			if($result == 0) {
				self::ajax_ouput(300, '操作失败！');
			} else {
				self::ajax_ouput(200, '操作成功', '', 'closeCurrent');
			}
		}
		self::smarty() -> assign('min_password', MIN_PASSWORD);
		self::smarty()->display(self::$dirName . '/admin_modify_pwd.html');
	}
	//权限分配管理
	public static function authory(){
		if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		if(!in_array($_SESSION['admin']['username'], self::$_supper_auth)){
			self::ajax_ouput(300, '禁止访问');
		}
		$userid = intval($_GET['userid']);
		$authes = model_user::get_all_auth();
		$authes = self::build_tree($authes, 0);
		$user_auth = model_user::get_user_authes($userid);
		$user_authes = array();
		$str = "";
		if(!empty($user_auth)){
			foreach($user_auth as $v){
				$str .= "{$v['auth_id']},";
				$user_authes[$v['parent_id']][] = $v['auth_id'];
			}
		}
		$str = trim($str,',');
		$parents = array();
		if(!empty($str)){
			$parents_id = model_admin::get_parent_authority_id($str);
			if(!empty($parents_id)){
				foreach($parents_id as $v){
					$parents[] = $v['parent_id'];
				}
			}
		}
		self::smarty() -> assign('parents', $parents);
		self::smarty() -> assign('authes', $authes);
		self::smarty() -> assign('user_authes', $user_authes);
		self::smarty() -> assign('userid', $userid);
		self::smarty()->display(self::$dirName . '/admin_authory.html');
	}
	//权限修改
	public static function update_authory(){
		if(!model_admin::islogin()) {
    		self::goto_login();
    	}
		if(!in_array($_SESSION['admin']['username'], self::$_supper_auth)){
			self::ajax_ouput(300, '禁止访问');
		}
		$authes = self::get_auth_post();
		$userid = intval($_POST['userid']);
		$result = model_user::update_user_auth($userid, $authes);
		if(empty($result)) {
			self::ajax_ouput(300, '操作失败！');
		} else {
			self::ajax_ouput(200, '操作成功', '', 'closeCurrent');
		}
	}
	//获取POST数据
	private static function get_auth_post(){
		$data = $_POST['category'];
		$result = array();
		if(empty($data)){
			return $result;
		}
		foreach($data as $v){
			$values = $_POST['category_'.$v];
			if(empty($values)){
				continue;
			}
			foreach($values as $v1){
				$value = intval($v1);
				if($value)
					$result[] = $value;
			}
			
		}
		return array_unique($result);
	}
}
